package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.common.feign.product.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("wareSkuService")
@Slf4j
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareSkuEntity> wrapper = Wrappers.lambdaQuery();

        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotBlank(skuId)) {
            wrapper.eq(WareSkuEntity::getSkuId, skuId);
        }

        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotBlank(wareId)) {
            wrapper.eq(WareSkuEntity::getWareId, wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addStock(List<WareSkuEntity> wareSkuEntities) {
        List<WareSkuEntity> updates = new ArrayList<>();
        List<WareSkuEntity> inserts = new ArrayList<>();
        for (WareSkuEntity wareSkuEntity : wareSkuEntities) {
            WareSkuEntity skuEntity = this.getOne(Wrappers.<WareSkuEntity>lambdaQuery()
                    .eq(WareSkuEntity::getSkuId, wareSkuEntity.getSkuId())
                    .eq(WareSkuEntity::getWareId, wareSkuEntity.getWareId()));
            if (skuEntity != null) {
                skuEntity.setStock(skuEntity.getStock() + wareSkuEntity.getStock());
                updates.add(skuEntity);
            } else {
                wareSkuEntity.setStockLocked(0);
                Long skuId = wareSkuEntity.getSkuId();
                try {
                    // 远程调用商品模块, 获取 skuName, 对此冗余字段调用失败不回滚事务, 所以try-catch
                    // TODO 或者使用服务降级
                    R result = productFeignService.info(skuId);
                    if (result.getCode().equals(0)) {
                        System.out.println("=====>" + result.get("skuInfo").getClass());
                        System.out.println("=====>" + result.get("skuInfo"));
                        Map<String, Object> skuInfo = (Map<String, Object>) result.get("skuInfo");
                        wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                    } else {
                        log.info((String) result.get("msg"));
                    }
                } catch (Exception e) {
                    log.info("远程调用商品模块失败, skuId: {}, e: {}", skuId, e.getMessage());
                }
                inserts.add(wareSkuEntity);
            }
        }

        // 修改有库存的
        this.updateBatchById(updates);

        // 保存没有的库存信息
        this.saveBatch(inserts);

    }

}
